package com.laikan.reader.core.utils;

import cn.sharesdk.framework.ShareSDK;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.VersoBean;
import com.socks.library.KLog;
import org.json.JSONObject;
import thirdparty.cn.sharesdk.onekeyshare.OnekeyShare;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/10/11.
 */
public class ShareSdkReadBookShare {
    protected static long mRequestInternalTime;
    private static ShareReadListener shareReadListener;
    private static boolean mIsRequestShareFinish = true;

    private static boolean internalTime(long currentTime) {
        if (mRequestInternalTime > currentTime) {
            return true;
        }
        return false;
    }

    /**
     * 获取封底页
     *
     * @param bookId
     */
    public static void readBookShare(final String bookId, ShareReadListener listener, final BasicActivity activity) {
        shareReadListener = listener;
        if (internalTime(System.currentTimeMillis()) || !mIsRequestShareFinish) {
            return;
        }
        mRequestInternalTime = System.currentTimeMillis() + 2000;

        String url;
        if (SystemUtil.isLogin()) {
            url = APIProtocol.getRootURL2() + "shareV2/" + bookId + "?ch=1&userId=" + SPUtil.getString("user_id", "");
        }else {
            url = APIProtocol.getRootURL2() + "shareV2/" + bookId + "?ch=1";
        }

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                mIsRequestShareFinish = false;
                KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    BaseDataBean<VersoBean> result;
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<VersoBean>>() {
                    }.getType();

                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            if(shareReadListener != null)shareReadListener.onError();
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            showShare(bookId, result.getData().getTitle(), result.getData().getContent(), result.getData().getImgUrl(), result.getData().getShareId(), result.getData
                                ().getUserId());
                        }
                    }else {
                        if(shareReadListener != null)shareReadListener.onError();
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }

                }catch (Exception e) {
                    if(shareReadListener != null)shareReadListener.onError();
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if(shareReadListener != null)shareReadListener.onError();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {
                mIsRequestShareFinish = true;
            }
        };

        Requester requester = new Requester();
        requester.setUrl(url);
//        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(url, null, null, requestListener);
    }

    public static void shareArticle(final String articleId, ShareReadListener listener, final BasicActivity activity) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("shorteId", articleId);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                mIsRequestShareFinish = false;
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : httpResponse : " + httpResponse.responseContent);
                try {
                    JSONObject jsonObject = new JSONObject(httpResponse.responseContent);
                    if (Integer.parseInt(Constants.RESULT_OK) == jsonObject.getInt("result")) {
                        JSONObject jsonObjectData = jsonObject.getJSONObject("data");
                        String title = jsonObjectData.getString("title");
                        String img = jsonObjectData.getString("img");
                        String url = jsonObjectData.getString("url");
                        String intro = jsonObjectData.getString("intro");
                        showArticleShare(articleId, title, intro, img, url);
                    }else {
                        if(shareReadListener != null)shareReadListener.onError();
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    if(shareReadListener != null)shareReadListener.onError();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if(shareReadListener != null)shareReadListener.onError();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {
                mIsRequestShareFinish = true;
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.share_article_LinkUrl);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    }

    /**
     * 分享
     */
    public static void showShare(String book_id, String bookName, String content, String imageUrl, String shareId, String userId) {
        String shareUrl = APIProtocol.shareLinkUrl + "shareBookId=" + shareId + "&bookId=" + book_id + "&userId=" + userId;
        ShareSDK.initSDK(BasicApplication.getInstance());
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
        // oks.setNotification(R.drawable.ic_launcher,
        // getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(bookName);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(shareUrl);
        // text是分享文本，所有平台都需要这个字段
        // oks.setText("我是分享文本");
        String str = "";
        if (content.length() > 119) {
            str = content.substring(0, 118) + "...";
        }else {
            str = content;
        }
        oks.setText(str);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        // oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");//
        // 确保SDcard下面存在此张图片
        oks.setImageUrl(imageUrl);//
        // 确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(shareUrl);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(imageUrl);
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(BasicApplication.getInstance().getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(shareUrl);
        // 启动分享GUI
        oks.show(BasicApplication.getInstance());
        if(shareReadListener != null)shareReadListener.onSuccess();
    }

    public static void showArticleShare(String articleId, String articleName, String intro, String imageUrl, String siteUrl) {
        ShareSDK.initSDK(BasicApplication.getInstance());
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
        // oks.setNotification(R.drawable.ic_launcher,
        // getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(articleName);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(siteUrl);
        // text是分享文本，所有平台都需要这个字段
        // oks.setText("我是分享文本");
        String str = "";
        if (intro.length() > 119) {
            str = intro.substring(0, 118) + "...";
        }else {
            str = intro;
        }
        oks.setText(str);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        // oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");//
        // 确保SDcard下面存在此张图片
        oks.setImageUrl(imageUrl);//
        // 确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(siteUrl);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(imageUrl);
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(BasicApplication.getInstance().getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(siteUrl);
        // 启动分享GUI
        oks.show(BasicApplication.getInstance());
        if(shareReadListener != null)shareReadListener.onSuccess();
    }

    public interface ShareReadListener {
        public void onSuccess();
        public void onError();
    }
}
